<template>
	<view class="container">
		<!-- 头部区域（固定） -->
		<view class="fixed-header">
			<view class="tabs">
				<view class="tab-item" :class="{ active: currentTab === 0 }" @click="switchTab(0)">待审核</view>
				<view class="tab-item" :class="{ active: currentTab === 1 }" @click="switchTab(1)">待处理</view>
				<view class="tab-item" :class="{ active: currentTab === 2 }" @click="switchTab(2)">待验证</view>
				<view class="tab-item" :class="{ active: currentTab === 3 }" @click="switchTab(3)">已完成</view>
				<view class="tab-line" :style="{ left: tabLineLeft }"></view>
			</view>
			
			<view class="search-box">
				<view class="search-input">
					<text class="search-icon">🔍</text>
					<input type="text" placeholder="搜索隐患描述" v-model="searchKey" @confirm="search" />
					<text class="search-clear" v-if="searchKey" @click="clearSearch">×</text>
				</view>
				<view class="search-btn" @click="search">搜索</view>
				<text class="filter-btn" @click="showFilter = true">筛选</text>
			</view>
		</view>
		
		<!-- 中间滚动区域 -->
		<scroll-view 
			scroll-y 
			enable-back-to-top
			show-scrollbar
			:scroll-with-animation="true"
			class="scrollable-content" 
			:style="{ height: contentHeight + 'px' }"
			@scrolltolower="onScrollToBottom"
		>
			<view class="empty-tip" v-if="hazardList.length === 0">
				<text>暂无相关隐患信息</text>
			</view>
			
			<view class="danger-item" v-for="(item, index) in hazardList" :key="index" @click="navToDetail(item)">
				<view class="danger-header">
					<view class="danger-tag" :data-type="getTypeText(item.typeId)">{{getTypeText(item.typeId)}}</view>
					<view class="danger-status" :class="'status-' + item.status">{{getStatusText(item.status)}}</view>
				</view>
				<view class="danger-title">{{item.hazardDesc}}</view>
				<view class="danger-info">
					<text class="danger-location">{{item.hazardLocation}}</text>
					<text class="danger-time">{{formatTime(item.discoveryTime)}}</text>
				</view>
				<view class="danger-footer">
					<view class="handle-user" v-if="item.handler">
						<text>处理人：{{item.handler}}</text>
					</view>
					<view class="feedback-status" v-if="item.tishi">
						<text>反馈状态：{{item.tishi}}</text>
					</view>
					<view class="danger-btn" v-if="item.status === 1" @click.stop="goToProcess(item)">立即处理</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 底部分页组件（固定） -->
		<view class="fixed-pagination" v-if="hazardList.length > 0">
			<view class="records-info">共 {{hazardList.length}} 条记录</view>
			<view class="pagination-controls">
				<view 
					class="page-btn prev" 
					:class="{ disabled: currentPage <= 1 }" 
					@click="prevPage"
				>上一页</view>
				<view class="current-page">{{currentPage}} / {{Math.ceil(hazardList.length / pageSize) || 1}}</view>
				<view 
					class="page-btn next" 
					:class="{ disabled: currentPage >= totalPages }" 
					@click="nextPage"
				>下一页</view>
			</view>
		</view>
		
		<!-- 筛选弹窗 -->
		<view class="filter-mask" v-if="showFilter" @click="showFilter = false">
			<view class="filter-panel" @click.stop>
				<view class="filter-header">
					<text class="filter-title">筛选</text>
					<text class="filter-close" @click="showFilter = false">×</text>
				</view>
				<view class="filter-content">
					<view class="filter-item">
						<text class="filter-label">隐患类型</text>
						<view class="filter-options">
							<view class="filter-option" :class="{ active: hazardTypeId === null }" @click="hazardTypeId = null">全部</view>
							<view class="filter-option" 
								v-for="(type, index) in hazardTypes" 
								:key="index" 
								:class="{ active: hazardTypeId === type.id }" 
								@click="hazardTypeId = type.id">
								{{type.typeName}}
							</view>
						</view>
					</view>
				</view>
				<view class="filter-buttons">
					<view class="filter-reset" @click="resetFilter">重置</view>
					<view class="filter-confirm" @click="confirmFilter">确定</view>
				</view>
			</view>
		</view>
		
		<!-- 底部添加按钮 -->
		<view class="add-btn" @click="addDanger">
			<text class="add-icon">+</text>
			<text>新增隐患</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				currentTab: 0, // 当前选项卡：0-待审核，1-待处理，2-待验证，3-已完成
				tabLineLeft: '12.5%',
				searchKey: '', // 搜索关键词，对应hazardDesc
				hazardTypeId: null, // 隐患类型ID筛选
				showFilter: false,
				contentHeight: 0, // 内容区域高度
				windowHeight: 0, // 窗口高度
				
				// 分页相关
				currentPage: 1, // 当前页码
				pageSize: 10, // 每页显示条数，与后端默认一致
				jumpPage: "1", // 跳转页输入框
				total: 0, // 总记录数
				
				// 数据
				hazardList: [], // 当前页数据
				hazardTypes: [] // 隐患类型列表
			};
		},
		computed: {
			// 总页数
			totalPages() {
				// 使用实际数据长度来计算总页数，避免依赖后端返回的total
				return Math.ceil(this.hazardList.length / this.pageSize) || 1;
			},
			// 显示的页码
			displayPageNumbers() {
				const total = this.totalPages;
				const current = this.currentPage;
				
				// 最多显示5个页码按钮
				if (total <= 5) {
					// 总页数小于等于5，直接返回1到total的数组
					return Array.from({ length: total }, (_, i) => i + 1);
				} else {
					// 当前页在前3页
					if (current <= 3) {
						return [1, 2, 3, 4, 5];
					}
					// 当前页在后3页
					else if (current >= total - 2) {
						return [total - 4, total - 3, total - 2, total - 1, total];
					}
					// 当前页在中间
					else {
						return [current - 2, current - 1, current, current + 1, current + 2];
					}
				}
			}
		},
		created() {
			this.initLayout();
			this.getHazardTypes(); // 获取隐患类型列表
			this.loadHazardList(); // 加载隐患列表
		},
		methods: {
			// 初始化布局
			initLayout() {
				// 获取系统信息
				uni.getSystemInfo({
					success: (res) => {
						this.windowHeight = res.windowHeight;
						// 计算内容区域高度
						this.calcContentHeight();
						// 监听窗口大小变化
						window.addEventListener('resize', this.handleResize);
					}
				});
			},
			
			// 窗口大小变化处理
			handleResize() {
				this.calcContentHeight();
			},
			
			// 计算内容区域高度
			calcContentHeight() {
				// 头部高度(tabs+搜索框)
				const headerHeight = uni.upx2px(250); 
				// 底部导航栏高度
				const tabBarHeight = uni.upx2px(100);
				// 分页控件高度
				const paginationHeight = uni.upx2px(120);
				
				// 计算内容区域高度
				this.contentHeight = this.windowHeight - headerHeight - paginationHeight - tabBarHeight;
			},
			
			// 滚动到底部触发
			onScrollToBottom() {
				console.log('滚动到底部');
				// 如果当前页小于总页数，可以自动加载下一页
				if (this.currentPage < this.totalPages) {
					this.nextPage();
				}
			},
			
			// 获取隐患类型列表
			getHazardTypes() {
				uni.request({
					url: 'http://172.20.10.3:9527/security/hazardtype/list',
					method: 'GET',
					success: (res) => {
						if (res.statusCode === 200 && res.data.code === 200) {
							this.hazardTypes = res.data.data;
							console.log('获取隐患类型成功:', this.hazardTypes);
						} else {
							console.error('获取隐患类型失败:', res.data);
							uni.showToast({
								title: '获取隐患类型失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('请求隐患类型接口失败:', err);
					}
				});
			},
			
			// 加载隐患列表
			loadHazardList() {
				uni.showLoading({
					title: '加载中...'
				});
				
				// 构建请求URL和参数
				let url = `http://172.20.10.3:9527/security/hazard/page?pageNum=${this.currentPage}&pageSize=${this.pageSize}&status=${this.currentTab}`;
				
				// 添加搜索条件
				if (this.searchKey) {
					url += `&hazardDesc=${encodeURIComponent(this.searchKey)}`;
				}
				
				// 添加类型筛选
				if (this.hazardTypeId !== null) {
					url += `&typeId=${this.hazardTypeId}`;
				}
				
				uni.request({
					url: url,
					method: 'GET',
					success: (res) => {
						uni.hideLoading();
						
						if (res.statusCode === 200 && res.data.code === 200) {
							const data = res.data.data;
							this.hazardList = data.records;
							
							// 修正total计算，如果后端返回的total为0但有数据，使用数据长度
							this.total = data.total > 0 ? data.total : data.records.length;
							
							// 如果当前页没有数据且不是第一页，尝试加载上一页
							if (this.hazardList.length === 0 && this.currentPage > 1) {
								this.currentPage--;
								this.jumpPage = this.currentPage.toString();
								this.loadHazardList();
							}
						} else {
							this.hazardList = [];
							this.total = 0;
							console.error('获取隐患列表失败:', res.data);
							uni.showToast({
								title: '获取列表失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						this.hazardList = [];
						this.total = 0;
						console.error('请求隐患列表接口失败:', err);
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 切换标签页
			switchTab(index) {
				this.currentTab = index;
				// 更新标签线位置 - 四个选项卡，每个占25%
				const tabWidth = 25; // 每个选项卡宽度占比
				this.tabLineLeft = (tabWidth / 2 + index * tabWidth) + '%';
				this.currentPage = 1; // 重置为第一页
				this.jumpPage = "1";
				this.loadHazardList(); // 重新加载数据
			},
			
			// 获取类型文本
			getTypeText(typeId) {
				if (!typeId) {
					// 根据描述猜测类型
					if (this.hazardList && this.hazardList.some(item => item.typeId === typeId)) {
						const item = this.hazardList.find(item => item.typeId === typeId);
						if (item.hazardDesc && item.hazardDesc.includes('消防')) return '消防安全';
						if (item.hazardDesc && item.hazardDesc.includes('电')) return '用电安全';
						if (item.hazardDesc && item.hazardDesc.includes('道路') || item.hazardDesc && item.hazardDesc.includes('交通')) return '交通安全';
						if (item.hazardDesc && item.hazardDesc.includes('设备')) return '设施安全';
					}
					return '其他';
				}
				
				const type = this.hazardTypes.find(t => t.id === typeId);
				if (type) {
					return type.typeName;
				} else {
					// 根据typeId返回默认类型名称
					const typeMap = {
						1: '消防安全',
						2: '用电安全',
						3: '交通安全',
						4: '设施安全',
						5: '治安安全'
					};
					return typeMap[typeId] || '其他';
				}
			},
			
			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					0: '待审核',
					1: '待处理',
					2: '待验证',
					3: '已完成'
				};
				return statusMap[status] || '未知';
			},
			
			// 格式化时间
			formatTime(timestamp) {
				if (!timestamp) return '';
				
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hour = date.getHours().toString().padStart(2, '0');
				const minute = date.getMinutes().toString().padStart(2, '0');
				
				return `${year}-${month}-${day} ${hour}:${minute}`;
			},
			
			// 导航到详情页
			navToDetail(item) {
				uni.navigateTo({
					url: `/pages/hidden-danger/detail?id=${item.id}`
				});
			},
			
			// 清空搜索
			clearSearch() {
				this.searchKey = '';
				this.currentPage = 1;
				this.jumpPage = "1";
				this.loadHazardList();
			},
			
			// 搜索
			search() {
				this.currentPage = 1;
				this.jumpPage = "1";
				this.loadHazardList();
			},
			
			// 重置筛选
			resetFilter() {
				this.hazardTypeId = null;
			},
			
			// 确认筛选
			confirmFilter() {
				this.showFilter = false;
				this.currentPage = 1;
				this.jumpPage = "1";
				this.loadHazardList();
			},
			
			// 处理隐患
			handleDanger(item) {
				uni.showModal({
					title: '确认处理',
					content: `是否确认处理此隐患？`,
					success: (res) => {
						if (res.confirm) {
							// 发送请求修改状态
							uni.showLoading({
								title: '处理中...'
							});
							
							uni.request({
								url: `http://172.20.10.3:9527/security/hazard/updateStatus`,
								method: 'POST',
								data: {
									id: item.id,
									status: 2, // 更新为待验证状态
									handler: uni.getStorageSync('userInfo')?.id || '' // 使用当前登录用户ID
								},
								success: (res) => {
									uni.hideLoading();
									if (res.statusCode === 200 && res.data.code === 200) {
										uni.showToast({
											title: '处理成功',
											icon: 'success'
										});
										// 重新加载数据
										this.loadHazardList();
									} else {
										uni.showToast({
											title: res.data.message || '处理失败',
											icon: 'none'
										});
									}
								},
								fail: (err) => {
									uni.hideLoading();
									console.error('处理隐患失败:', err);
									uni.showToast({
										title: '网络请求失败',
										icon: 'none'
									});
								}
							});
						}
					}
				});
			},
			
			// 跳转到处理页面
			goToProcess(item) {
				uni.navigateTo({
					url: `/pages/hidden-danger/process?id=${item.id}`
				});
			},
			
			// 添加隐患
			addDanger() {
				uni.navigateTo({
					url: '/pages/hidden-danger/add'
				});
			},
			
			// 分页方法
			// 上一页
			prevPage() {
				if (this.currentPage > 1) {
					this.currentPage--;
					this.jumpPage = this.currentPage.toString();
					this.loadHazardList();
				}
			},
			// 下一页
			nextPage() {
				if (this.currentPage < this.totalPages) {
					this.currentPage++;
					this.jumpPage = this.currentPage.toString();
					this.loadHazardList();
				}
			},
			// 跳转到指定页
			goToPage(page) {
				if (page >= 1 && page <= this.totalPages) {
					this.currentPage = page;
					this.jumpPage = page.toString();
					this.loadHazardList();
				}
			},
			// 验证跳转页输入
			validateJumpPage() {
				let page = parseInt(this.jumpPage);
				if (isNaN(page) || page < 1) {
					this.jumpPage = "1";
				} else if (page > this.totalPages) {
					this.jumpPage = this.totalPages.toString();
				}
			}
		}
	}
</script>

<style lang="scss">
	.container {
		background-color: #f5f6fa;
		min-height: 100vh;
		position: relative;
		display: flex;
		flex-direction: column;
	}
	
	.fixed-header {
		position: sticky;
		top: 0;
		left: 0;
		right: 0;
		z-index: 10;
		background-color: #fff;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.tabs {
		display: flex;
		background-color: #fff;
		height: 100rpx;
		position: relative;
		border-bottom: 1px solid #f0f0f0;
	}
	
	.tab-item {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 30rpx;
		color: #666;
		position: relative;
	}
	
	.tab-item.active {
		color: #1a4380;
		font-weight: bold;
	}
	
	.tab-line {
		position: absolute;
		width: 60rpx;
		height: 6rpx;
		background-color: #1a4380;
		bottom: 0;
		left: 12.5%;
		transform: translateX(-50%);
		border-radius: 3rpx;
		transition: left 0.3s;
	}
	
	.search-box {
		padding: 20rpx 30rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
	}
	
	.search-input {
		flex: 1;
		height: 80rpx;
		background-color: #f5f5f5;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		margin-right: 20rpx;
	}
	
	.search-icon {
		margin-right: 10rpx;
		font-size: 28rpx;
	}
	
	.search-input input {
		flex: 1;
		height: 100%;
		font-size: 28rpx;
	}
	
	.search-clear {
		width: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		color: #999;
	}
	
	.search-btn {
		height: 80rpx;
		padding: 0 30rpx;
		background-color: #1a4380;
		color: #fff;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		margin-right: 20rpx;
	}
	
	.filter-btn {
		font-size: 28rpx;
		color: #1a4380;
	}
	
	.scrollable-content {
		flex: 1;
		padding: 20rpx 30rpx;
		overflow-y: auto;
		-webkit-overflow-scrolling: touch;
		position: relative;
		overflow-anchor: auto;
	}
	
	.danger-item {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		transition: transform 0.2s;
		
		&:active {
			transform: scale(0.98);
		}
	}
	
	.danger-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 16rpx;
	}
	
	.danger-tag {
		padding: 6rpx 16rpx;
		border-radius: 30rpx;
		font-size: 24rpx;
		background-color: #f5f5f5;
		color: #666;
		
		&.tag-fire, &[data-type="消防安全"] {
			background-color: #fff2f0;
			color: #ff4d4f;
			border: 1px solid rgba(255, 77, 79, 0.3);
		}
		
		&.tag-facility, &[data-type="设施安全"] {
			background-color: #e6f7ff;
			color: #1890ff;
			border: 1px solid rgba(24, 144, 255, 0.3);
		}
		
		&.tag-electric, &[data-type="用电安全"] {
			background-color: #fff7e6;
			color: #fa8c16;
			border: 1px solid rgba(250, 140, 22, 0.3);
		}
		
		&.tag-traffic, &[data-type="交通安全"] {
			background-color: #f6ffed;
			color: #52c41a;
			border: 1px solid rgba(82, 196, 26, 0.3);
		}
		
		&[data-type="治安安全"] {
			background-color: #f9f0ff;
			color: #722ed1;
			border: 1px solid rgba(114, 46, 209, 0.3);
		}
		
		&[data-type="其他"] {
			background-color: #f5f5f5;
			color: #666;
			border: 1px solid rgba(102, 102, 102, 0.3);
		}
	}
	
	.danger-status {
		padding: 4rpx 16rpx;
		border-radius: 100rpx;
		font-size: 24rpx;
		
		&.status-0 { // 待审核
			background-color: #e6f7ff;
			color: #1890ff;
		}
		
		&.status-1 { // 待处理
			background-color: #fff2e8;
			color: #fa8c16;
		}
		
		&.status-2 { // 待验证
			background-color: #f0f5ff;
			color: #597ef7;
		}
		
		&.status-3 { // 已完成
			background-color: #f6ffed;
			color: #52c41a;
		}
	}
	
	.danger-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 16rpx;
	}
	
	.danger-info {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}
	
	.danger-location {
		font-size: 26rpx;
		color: #666;
		max-width: 70%;
	}
	
	.danger-time {
		font-size: 26rpx;
		color: #999;
	}
	
	.danger-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-top: 1px solid #f5f5f5;
		padding-top: 20rpx;
	}
	
	.handle-user {
		font-size: 26rpx;
		color: #666;
	}
	
	.feedback-status {
		font-size: 26rpx;
		color: #666;
		margin-left: 20rpx;
	}
	
	.danger-btn {
		padding: 10rpx 30rpx;
		background-color: #1a4380;
		color: #fff;
		border-radius: 100rpx;
		font-size: 24rpx;
	}
	
	.empty-tip {
		text-align: center;
		padding: 100rpx 0;
		color: #999;
		font-size: 28rpx;
	}
	
	.fixed-pagination {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(255, 255, 255, 0.95);
		padding: 20rpx 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 5;
		backdrop-filter: blur(10px);
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-top: 1rpx solid #eee;
	}
	
	.records-info {
		font-size: 24rpx;
		color: #999;
	}
	
	.pagination-controls {
		display: flex;
		align-items: center;
	}
	
	.page-btn {
		padding: 8rpx 20rpx;
		font-size: 26rpx;
		color: #fff;
		background-color: #1a4380;
		border-radius: 8rpx;
		margin: 0 10rpx;
		
		&.disabled {
			background-color: #ccc;
			color: #fff;
			opacity: 0.7;
		}
	}
	
	.current-page {
		font-size: 26rpx;
		margin: 0 20rpx;
		color: #333;
	}
	
	.add-btn {
		position: fixed;
		bottom: 140rpx;
		right: 30rpx;
		width: 120rpx;
		height: 120rpx;
		background: #1a4380;
		border-radius: 50%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #fff;
		font-size: 26rpx;
		box-shadow: 0 6rpx 16rpx rgba(26, 67, 128, 0.3);
		z-index: 6;
	}
	
	.add-icon {
		font-size: 40rpx;
		line-height: 1;
		margin-bottom: 6rpx;
	}
	
	.filter-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 100;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.filter-panel {
		width: 80%;
		background-color: #fff;
		border-radius: 20rpx;
		overflow: hidden;
	}
	
	.filter-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1px solid #f5f5f5;
	}
	
	.filter-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.filter-close {
		font-size: 40rpx;
		color: #999;
	}
	
	.filter-content {
		padding: 30rpx;
	}
	
	.filter-item {
		margin-bottom: 30rpx;
	}
	
	.filter-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
		display: block;
	}
	
	.filter-options {
		display: flex;
		flex-wrap: wrap;
		margin: 0 -10rpx;
	}
	
	.filter-option {
		margin: 10rpx;
		padding: 12rpx 24rpx;
		border-radius: 30rpx;
		font-size: 26rpx;
		background-color: #f5f5f5;
		color: #666;
		
		&.active {
			background-color: #1a4380;
			color: #fff;
		}
	}
	
	.filter-buttons {
		display: flex;
		border-top: 1px solid #f5f5f5;
	}
	
	.filter-reset {
		flex: 1;
		height: 90rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		color: #666;
		background-color: #f5f5f5;
	}
	
	.filter-confirm {
		flex: 1;
		height: 90rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		color: #fff;
		background-color: #1a4380;
	}
</style> 